/**
 * @author zj
 * @desc:
 * @date: 2024/8/4 04
 */

import axios from "axios";
import { useToken } from "@/store/index.js";
import router from "@/router";
import { refreshToken } from "@/request/api/login/index.js"; // 修正导入路径

function redirectToLogin() {
  router.push({
    path: "/login",
    query: {
      redirect: router.currentRoute.value.fullPath,
    },
  });
}

const request = axios.create({
  baseURL: "/api",
  timeout: 20000,
});

request.interceptors.request.use((config) => {
  // 缓存 token store 实例
  const tokenStore = useToken();
  config.headers.Authorization =
    tokenStore.getToken() || sessionStorage.getItem("token") || "";
  return config;
});

// 是否正在刷新token
let isRefreshing = false;
// 重试队列
let requests = [];

// 处理重试队列中的请求
function processQueue(error, token = null) {
  requests.forEach((callback) => {
    if (error) {
      callback.reject(error);
    } else {
      callback.resolve(token);
    }
  });
  requests = [];
}

request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  async (error) => {
    // 缓存 token store 实例
    const tokenStore = useToken();
    const originalRequest = error.config;

    if (error.response) {
      // token过期处理
      if (error.response.status === 401 && !originalRequest._retry) {
        originalRequest._retry = true;

        // 如果有refresh token且不在刷新中
        if (tokenStore.refreshToken && !isRefreshing) {
          isRefreshing = true;

          try {
            // 使用refresh token获取新的access token
            const response = await refreshToken({
              refreshToken: tokenStore.refreshToken,
            });

            if (response.code === 500) {
              tokenStore.reset();
              redirectToLogin();
              processQueue(error, null);
              return Promise.reject(error);
            }

            const token = response.data;

            // 更新token
            tokenStore.setToken(token);

            // 更新默认请求头
            request.defaults.headers.Authorization = token;

            // 重新发送队列中的请求
            processQueue(null, token);

            // 重新发送原始请求
            return request(originalRequest);
          } catch (refreshError) {
            // 刷新token失败，跳转到登录页
            tokenStore.reset();
            redirectToLogin();
            processQueue(refreshError, null);
            return Promise.reject(refreshError);
          } finally {
            isRefreshing = false;
          }
        } else if (isRefreshing) {
          // 如果正在刷新token，将请求加入队列
          return new Promise((resolve, reject) => {
            requests.push({ resolve, reject });
          })
            .then((token) => {
              originalRequest.headers.Authorization = token;
              return request(originalRequest);
            })
            .catch((err) => {
              return Promise.reject(err);
            });
        } else {
          // 没有refresh token，直接跳转到登录页
          tokenStore.reset();
          redirectToLogin();
        }
      }
    }

    return Promise.reject(error);
  },
);

export default request;
